package com.zhai.test.algorithm.array;

/**
 * @Description: 搜索插入位置
 * @ClassName: MiddleQuery
 * @Author: zhaiyongxin
 * @Date: 2025/3/11 17:50
 * @Version: 1.0
 */
public class FirstAndLastPosition {
    public static void main(String[] args) {
        int[] array  = new int[]{1,1,2};
        int target = 1;
        int[] result = getResult(array, target);
        System.out.println(result);
    }

    public static int[] getResult(int[] array, int target) {
        int[] result = new int[]{-1, -1};
        int position = getTargetIdx1(array, target);
        if (position == -1) {
            return result;
        }
        int leftPos = position;
        int rightPos = position;
        int left = position;
        int right = position;
        while (left-1 >=0 && array[left-1] == target) {
            left--;
        }
        while (right+1 < array.length && array[right+1] == target) {
            right++;
        }
        result = new int[]{left, right};
        return result;
    }

    public static int getTargetIdx1(int[] array, int target) {
        int left = 0;
        int right = array.length - 1;
        while (left <= right) {
            int middle = (left + right) / 2;
            if (target == array[middle]) {
                return middle;
            } else if (target < array[middle]) {
                right = middle - 1;
            } else {
                left = middle + 1;
            }
        }
        return -1;
    }


}
